package com.wennn.top.generator.util;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@Slf4j
public class GeneratorBuilder {

    private String defaultParentPackage = "com.wennn.top";

    private String stdJavaPackagePath="/src/main/java";

    private String stdResourcePackagePath="/src/main/resources";

    @Getter
    @Setter
    private String projectPath;

//    private String tempPath = "";
    // 如果模板引擎是 freemarker
    @Getter
    @Setter
    private String templatePath = "/templates/mapper.xml.ftl";
    // 如果模板引擎是 velocity
    // String templatePath = "/templates/mapper.xml.vm";

    /**工程路径*/
    @Getter
    @Setter
    private String defaultProjectPath=System.getProperty("user.dir");


    /**全局配置*/
    @Getter
    private GlobalConfig globalConfig;

    /**包配置*/
    @Getter
    private PackageConfig packageConfig;

    /**数据源配置*/
    @Getter
    private DataSourceConfig dataSourceConfig;

    @Getter
    private StrategyConfig strategy;

    TemplateConfig templateConfig = new TemplateConfig();

    /**生成器*/
    private AutoGenerator mpg;

    private GeneratorBuilder(){
        this.mpg = new AutoGenerator();
        // 策略配置
        this.strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);

        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");

        strategy.setControllerMappingHyphenStyle(true);


    }

    public static GeneratorBuilder builder(String userName, String password, String url, String driverName){
        return new GeneratorBuilder().setDatasource(userName,password,url,driverName);
    }

    public GeneratorBuilder setDatasource(String superEntityClass, String superControllerClass){
        // 你自己的父类实体,没有就不用设置!
        strategy.setSuperEntityClass(superEntityClass);
        // 公共父类 你自己的父类控制器,没有就不用设置!
        strategy.setSuperControllerClass(superControllerClass);
        return this;
    }

    /**
     * 数据源配置
     * @param userName
     * @param password
     * @param url
     * @param driverName
     * @return
     */
    public GeneratorBuilder setDatasource(String userName, String password, String url, String driverName){
        this.dataSourceConfig = new DataSourceConfig();
        this.dataSourceConfig.setUsername(userName);
        this.dataSourceConfig.setPassword(password);
        this.dataSourceConfig.setUrl(url);
        this.dataSourceConfig.setDriverName(driverName);
        return this;
    }

    /**
     * 设置全局信息
     * @param projectPath
     * @param author
     * @return
     */
    public GeneratorBuilder setGlobalConfig(String projectPath, String author){
        this.projectPath = null == projectPath?defaultProjectPath:projectPath;
        // 全局配置
        this.globalConfig = new GlobalConfig();
        this.globalConfig.setOutputDir(this.projectPath + stdJavaPackagePath);
        this.globalConfig.setAuthor(author);
        this.globalConfig.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(this.globalConfig);
        return this;
    }

    /**
     *
     * @param projectPath
     * @param moduleName
     * @return
     */
    public GeneratorBuilder setPackageConfig(String moduleName, String parentPackage){
        this.packageConfig = new PackageConfig();
        this.packageConfig.setModuleName(moduleName);
        parentPackage = parentPackage == null?defaultParentPackage:parentPackage;
        this.packageConfig.setParent(parentPackage);
        return this;
    }

    public GeneratorBuilder enableSwagger(){
        this.getGlobalConfig().setSwagger2(true);
        return this;
    }

    private List<FileOutConfig> getOutConfig(String projectPath, PackageConfig pc){
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(this.templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + stdResourcePackagePath+"/mybatis/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录");
                return false;
            }
        });
        */
        return focList;
    }


    public TemplateConfig getTemplateConfig(){
        return this.templateConfig;
    }

//    private TemplateConfig builderTemplateConfig(){
//
//        // 配置自定义输出模板
//        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
//        // templateConfig.setEntity("templates/entity2.java");
//        // templateConfig.setService();
//        // templateConfig.setController();
//
//        templateConfig.setXml(null);
//        return templateConfig;
//    }


    public void build(String tableName){

        // 全局配置
        mpg.setGlobalConfig(this.globalConfig);

        // 数据源配置
        mpg.setDataSource(this.dataSourceConfig);

        // 包配置
        mpg.setPackageInfo(this.packageConfig);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 自定义输出配置
        cfg.setFileOutConfigList(this.getOutConfig(this.projectPath,this.packageConfig));
        cfg.getFileOutConfigList();
        mpg.setCfg(cfg);

        //设置模版
        mpg.setTemplate(getTemplateConfig());

        this.strategy.setInclude(tableName.split(","));
        this.strategy.setTablePrefix(this.packageConfig.getModuleName() + "_");
        mpg.setStrategy(this.strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}
